#include "Sound2D.h"
#include "AllocationManager.h"
#include "Audio.h"
#include "Error.h"

namespace Engine
{
	bool Sound2D::Load(const std::string& filename)
	{
		m_sound = TheAudio::Instance() ->m_audioEngine ->play2D(filename.c_str(), false, true, false, irrklang::ESM_AUTO_DETECT, true);

		if(m_sound)
		{
			#ifdef MEM_DEBUG
				TheAllocationManager::Instance() ->AddAllocation(Allocation(&m_sound, 4,__FILE__, __LINE__));
			#endif //MEM_DEBUG

			m_name = filename;
		}

		if(!m_sound) 
		{
			Error("Unable to load 2D Sound: " + filename);
			return false;
		}
		return true;
	}

	bool Sound2D::Load(rapidxml::xml_node <>* node)
	{
		if(!node ->first_node("FileName"))
		{
			Error("Unable to find Sound2D FilePath in xml file");
			return false;
		}

		return Load(node ->first_node("FileName") ->value());
	}

	void Sound2D::Play() 
	{
		if(m_sound) m_sound ->setIsPaused(false);
	}

	void Sound2D::Pause()
	{
		if(m_sound) m_sound ->setIsPaused(true);
	}

	void Sound2D::Stop() 
	{
		if(m_sound) m_sound ->stop();
	}

	bool Sound2D::IsPlaying() 
	{
		if(!m_sound) return false;
		return (!m_sound ->getIsPaused() && !m_sound ->isFinished());
	}

	void Sound2D::SetLoop(bool l)
	{
		if(m_sound) m_sound ->setIsLooped(l);
	}

	void Sound2D::SetVolume(float v)
	{
		if(m_sound) m_sound ->setVolume(v);
	}

	void Sound2D::SetTrackPos(float p)
	{
		if(m_sound) m_sound ->setPlayPosition(static_cast <unsigned int> (p * 1000.0f));
	}

	float Sound2D::GetVolume() const
	{
		if(m_sound) return m_sound ->getVolume();
		return 0.0f;
	}

	float Sound2D::GetTrackPos() const
	{
		float temp = 0.0f;

		if(m_sound)
		{
			temp = static_cast <float> (m_sound ->getPlayPosition()) ;
			temp *= 0.001f;
		}

		return temp;
	}

	float Sound2D::GetLength() const
	{
		float temp = 0.0f;

		if(m_sound)
		{
			temp = static_cast <float> (m_sound ->getPlayLength()) ;
			temp *= 0.001f;
		}

		return temp;
	}


	irrklang::ISoundEffectControl* Sound2D::GetController()
	{
		if(m_sound) return m_sound ->getSoundEffectControl();
		return nullptr;
	}


	Sound2D::~Sound2D()
	{
		if(m_sound)
		{
			#ifdef MEM_DEBUG
				TheAllocationManager::Instance() ->RemoveAllocation(m_sound);
			#endif //MEM_DEBUG

			m_sound ->drop();
		}
	}
}